package net.kaaass.tools.gradequery.network;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import net.kaaass.tools.gradequery.Mark;
import net.kaaass.tools.gradequery.captcha.Infer;
import net.kaaass.tools.gradequery.util.NetworkUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.File;
import java.io.IOException;

public class Query {
    public static String UA = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36";
    private static String URL = "http://cx.zjzs.net/exam/xyks201701/resault.aspx";
    public static int MAX_TRY = 5;
    // public static int TIMEOUT = 5000;

    private static String[] levelSorts = {"YWXK", "SXXK", "YYXK", "WLXK", "HXXK", "SWXK", "SZXK", "LSXK", "DLXK", "JSXK"};
    private static String[] markSorts = {"YYXN", "WLXN", "HXXN", "SWXN", "SZXN", "LSXN", "DLXN", "JSXN"};

    public static Mark query(String id, String examId) throws IOException {
        Mark result;
        String raw = "";
        for (int i = 0; i < MAX_TRY; i++) {
            try {
                raw = queryRawData(id, examId);
            } catch (Exception e) {
                System.out.format("尝试请求成绩错误，错误为：%s，重复第%d/%d次。\n", e.toString(), i + 1, MAX_TRY);
                if (i == MAX_TRY - 1)
                    throw new IOException("请求失败，达到最大请求次数限制。");
                continue;
            }
            break;
        }
        /*
        判断是否成功，本来打算用正则的，然而很懒w
         */
        if (raw.startsWith("<script>"))
            throw new IllegalArgumentException(raw.split("'", 3)[1] + ", 信息：" + id + "," + examId);
        /*
        使用Jsoup转为dom解析
         */
        result = new Mark(id, examId);
        Document dom = Jsoup.parse(raw);
        Element el;
        el = dom.getElementById("XM"); // 获取姓名
        result.setName(el.text());
        el = dom.getElementById("BMXH"); // 获取报名序号
        result.setReqId(el.text());
        String[] level = new String[levelSorts.length]; // 等第获取
        for (int i = 0; i < levelSorts.length; i++) {
            el = dom.getElementById(levelSorts[i]);
            if (el != null)
                level[i] = el.text();
        }
        result.setLevel(level);
        String[] mark = new String[markSorts.length]; // 赋分获取
        for (int i = 0; i < markSorts.length; i++) {
            el = dom.getElementById(markSorts[i]);
            if (el != null)
                mark[i] = el.text();
        }
        result.setMark(mark);
        return result;
    }

    public static String queryRawData(String id, String examId) {
        HttpResponse<String> response = null;
        String captcha;
        String cookie;
        String body;

        /*
        初始化
         */
        try {
            // cookie = String.format("ASP.NET_SessionId=%s; _gscu_1466624205=859375396ym2vg17;", StringUtil.randStr(24, StringUtil.SET_ENG + StringUtil.SET_NUM));
            cookie = "ASP.NET_SessionId=cwhuj1h3xivjcvmlvkjxissc; _gscu_1466624205=859375396ym2vg17;";

            /*
            验证码
            */
            File img_captcha = NetworkUtil.downloadCaptcha(cookie);  // 下载验证码
            captcha = Infer.read(img_captcha); // 识别验证码
            System.out.println("Succeeded read captcha: " + captcha);
            img_captcha.delete();  // 删除下载的验证码

            /*
            请求
             */
            body = String.format("ZKZH=%s&SFZH=%s&yzm=%s", examId, id, captcha);
            response = Unirest.post(URL)
                    .header("Cookie", cookie).header("User-Agent", UA).header("Connection", "Keep-Alive")
                    .header("Content-type", "application/x-www-form-urlencoded")
                    .body(body).asString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.getBody();
    }
}
